<template>
  <div class="upload-index">
    <input type="file" class="upload-index__transparent-input" :accept="accept" @change="handleImport" />
    <el-button icon="upload" :loading="loading" v-bind="attr">{{ loading ? '导入中...' : '导入' }}</el-button>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { http } from 'jax-node'

const props = defineProps({
  url: {
    type: String,
    default: '/system/file/import-xlsx',
  },
  attr: {
    type: Object,
    default: {}
  },
  accept: {
    type: String,
    default:
      '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel',
  },
})

const emits = defineEmits(['change'])

const zIndex = ref(16)
const loading = ref(false)

function handleImport(e) {
  if (!props.url) return ElMessage.error('上传地址不能为空')

  const formData = new FormData()
  const files = e.target.files

  formData.append('files', files[0])

  loading.value = true
  zIndex.value = -1

  http({
    url: '/system/upload',
    method: 'post',
    data: formData,
  })
    .then(res => {
      e.target.value = null

      const importFileUrl = res[0].url

      http({
        url: `${props.url}`,
        method: 'post',
        data: {
          // url: importFileUrl.slice(importFileUrl.indexOf('/uploads/')),
          url: importFileUrl
        },
        successMsg: '上传成功',
      })
        .then((res) => {
          emits('change', res)
        })
        .finally(() => {
          e.target.value = null
          loading.value = false
          zIndex.value = 16
        })
    })
    .catch(err => {
      console.log('err:', err)
      e.target.value = null
      loading.value = false
      zIndex.value = 16
    })
}
</script>

<style lang="scss" scoped>
.upload-index {
  position: relative;
  width: fit-content;
  height: fit-content;
  &:not(:last-child) {
    margin: 0 12px;
  }
  &__transparent-input {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: v-bind('zIndex');
    cursor: pointer;
    opacity: 0;

    // 隐藏
    &::-webkit-file-upload-button {
      visibility: hidden;
    }
  }
}
</style>
